import axios from 'axios'
import Vue from 'vue'

axios.defaults.timeout = 60000 // 设置超时时间

class HTTP {
  /**
   * @description: 提供外部使用的 request 方法，用于接口调用
   * @param {Object} param0
   * @return {Promise}
   */
  request ({ method, url, data, headers }) {
    return new Promise((resolve, reject) => {
      this._request({ method, url, data, headers, resolve, reject })
    })
  }

  /**
   * @description: 封装使用 axios 库的 _request 方法
   * @param {Object} param0
   */
  _request ({ method = 'GET', url, data = {}, headers = {}, resolve, reject }) {
    let params = {}
    if (method.toUpperCase() === 'GET') {
      // GET 请求使用 params
      params = data
      data = {}
    }
    if (headers && data) {
      const contentType = headers['Content-Type']
      if (contentType === 'application/x-www-form-urlencoded') {
        params = new URLSearchParams()
        for (let key in data) {
          params.append(key, data[key])
        }
        data = {}
      } else if (contentType === 'multipart/form-data') {
        let formData = new FormData()
        for (let key in data) {
          formData.append(key, data[key])
        }
        data = formData
      }
    }
    axios({
      url,
      method,
      data,
      params,
      headers: this._mergeHeaders(this._getHeaders(), headers)
    })
      .then(response => {
        const { data } = response
        resolve(data)
      })
      .catch(error => {
        const { response } = error
        if (response) {
          this._showErrorInfo(response)
          if (response.status === 401) {
            // 401 Unauthorized ，则返回登录页面
            // router.push('/login')
          }
        }
        reject(error)
      })
  }

  /**
   * @description: 获取 headers 字段
   * @return {Object}
   */
  _getHeaders () {
    const jsessionId =
      localStorage.getItem('jsessionId') ||
      sessionStorage.getItem('jsessionId') ||
      'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIwODgxNSIsIm9yZ05hbWUiOiLlrp7pqozlrqTkuI7oo4XlpIflpIQiLCJvcmdDb2RlIjoiNjIwMDAwMDAiLCJyb2xlSWQiOiIwMTZiNDVkMmZmODU0MDI4YjIxZjZiNDVhMmM3MDAxNSIsImFwcElkIjoiMDE2ODVlOTgzYmI0ZmY4MDgwODE2ODU5OGVkYTAwMDMiLCJjdXJyZW50VGltZU1pbGxpcyI6IjE2MDQ4OTI0OTYxNjMiLC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TljNmQxNGE0MDI4YjI1NTY5OTljNWVlMDAwMlwiLFwicm9sZV9jb2RlXCI6XCJzeXN0ZW1BZG1pblwiLFwicm9sZV9uYW1lXCI6XCLns7vnu5_nrqHnkIblkZhcIixcInZpZXdfbmFtZVwiOlwi5a6e6aqM5a6k5LiO6KOF5aSH5aSE6aaW6aG1XCIsXCJ2aWV3X3JlZ2lzdGVyX25hbWVcIjpcImxzbXNMYWJBbmRFcXVpcG1lbnRIb21lXCJ9XSIsImFjY291bnQiOiIwODgxNSIsIm9yZ0lkIjoiMDE2YjAyOTFiNTBlNDAyOGIyMTE2YjAyNzBhODAyMzEifQ.yYuQe-9tzqaEmycLJkeHwnRb-B0Un8dZnKDzlq-XwHA'
    if (jsessionId) {
      return {
        Authorization: jsessionId
      }
    } else {
      return {}
    }
  }

  /**
   * @description: 合并 headers 参数
   * @param {Object} defaultHeaders
   * @param {Object} headers
   */
  _mergeHeaders (defaultHeaders, headers) {
    return Object.assign({}, defaultHeaders, headers)
  }

  /**
   * @description: 显示错误信息
   * @param {Object} response
   */
  _showErrorInfo (response) {
    const { data, statusText } = response
    let errMsg = '接口异常，'
    if (data && data.content) {
      errMsg += data.content
    } else {
      errMsg += statusText
    }
    Vue.prototype.$Message.error(errMsg)
  }
}

export default HTTP
